<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="JavaScript最重要的底层链路逻辑之一，异步程序的执行逻辑">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解事件循环机制">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/interview_questions/js/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="JavaScript最重要的底层链路逻辑之一，异步程序的执行逻辑">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/javascript_event_loop.gif">
<meta property="og:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/eventloop-zhuanzhuan.jpg">
<meta property="article:published_time" content="2021-05-23T12:14:12.000Z">
<meta property="article:modified_time" content="2021-11-28T11:04:33.465Z">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/javascript_event_loop.gif">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/interview_questions/js/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入理解事件循环机制 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#JavaScript%E6%98%AF%E5%8D%95%E7%BA%BF%E7%A8%8B%E8%84%9A%E6%9C%AC%E8%AF%AD%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">JavaScript是单线程脚本语言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%98%AFJavaScript%E5%AE%BF%E4%B8%BB%E7%8E%AF%E5%A2%83%E4%B8%80%E5%A5%97%E5%8D%8F%E8%B0%83%E5%BC%82%E6%AD%A5%E7%A8%8B%E5%BA%8F%E6%89%A7%E8%A1%8C%E7%9A%84%E6%9C%BA%E5%88%B6"><span class="nav-number">2.</span> <span class="nav-text">事件循环是JavaScript宿主环境一套协调异步程序执行的机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E7%AE%80%E5%8D%95%E7%9A%84%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="nav-number">3.</span> <span class="nav-text">事件循环简单的运行流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%90%86%E8%A7%A3%E5%AE%8F%E4%BB%BB%E5%8A%A1-Task-%E4%B8%8E%E5%BE%AE%E4%BB%BB%E5%8A%A1-MicroTask"><span class="nav-number">4.</span> <span class="nav-text">理解宏任务(Task)与微任务(MicroTask)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BD%93%E5%89%8D%E5%AE%8F%E4%BB%BB%E5%8A%A1%E6%89%A7%E8%A1%8C%E5%AE%8C%E6%AF%95%EF%BC%88%E4%B8%94%E8%B0%83%E7%94%A8%E6%A0%88%E8%A2%AB%E6%B8%85%E7%A9%BA%E5%90%8E%EF%BC%89%E6%89%A7%E8%A1%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1"><span class="nav-number">4.1.</span> <span class="nav-text">当前宏任务执行完毕（且调用栈被清空后）执行微任务</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6%E4%B8%8EVue-nextTick-%E5%92%8CrequestAnimationFrame-%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="nav-number">5.</span> <span class="nav-text">事件循环机制与Vue.nextTick()和requestAnimationFrame()的关系</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%AA%E7%AB%9F%E4%B9%8B%E4%BA%8B"><span class="nav-number"></span> <span class="nav-text">未竟之事</span></a></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/interview_questions/js/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入理解事件循环机制
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-05-23 20:14:12" itemprop="dateCreated datePublished" datetime="2021-05-23T20:14:12+08:00">2021-05-23</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-11-28 19:04:33" itemprop="dateModified" datetime="2021-11-28T19:04:33+08:00">2021-11-28</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E7%81%AB%E6%98%9F%E8%AE%A1%E5%88%92/" itemprop="url" rel="index"><span itemprop="name">火星计划</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>2.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>2 分钟</span>
    </span>
</div>

            <div class="post-description">JavaScript最重要的底层链路逻辑之一，异步程序的执行逻辑</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="JavaScript是单线程脚本语言"><a href="#JavaScript是单线程脚本语言" class="headerlink" title="JavaScript是单线程脚本语言"></a>JavaScript是单线程脚本语言</h3><p>怎么理解“单线程”呢？如下代码所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 代码从上到下，逐句执行，控制台先输出1</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;1&#x27;</span>);</span><br><span class="line"></span><br><span class="line">alert(<span class="string">&#x27;2&#x27;</span>);</span><br><span class="line"><span class="comment">// 只要弹框没关闭，3是不会输出到控制台的，被阻断了</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;3&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>JSConf讲座中，Jake Archibald举了个很恰当的例子：</p>
<blockquote>
<p>JS的阻塞，就如同打喷嚏一样，人在打喷嚏的时候，视觉、听觉甚至思考都会会暂停</p>
</blockquote>
<p>打喷嚏的体验当然是糟糕的，如果页面经常打喷嚏被阻塞，也一样是难以想象的。可我们编程充斥着各种异步代码，比如通过<code>axios</code>发起请求，或者是<code>setTimeout</code>延迟执行代码，用户却感受不到被阻塞，这是为什么呢？答案就是事件循环(EventLoop)机制</p>
<h3 id="事件循环是JavaScript宿主环境一套协调异步程序执行的机制"><a href="#事件循环是JavaScript宿主环境一套协调异步程序执行的机制" class="headerlink" title="事件循环是JavaScript宿主环境一套协调异步程序执行的机制"></a>事件循环是JavaScript宿主环境一套协调异步程序执行的机制</h3><p>事件循环不属于JavaScript的范畴，并不在ECMAScript标准当中，甚至你在《JavaScript高级程序设计》红宝书当中，完全找不到相关内容。<br>实际上，事件循环机制定义在HTML标准当中，是JS宿主环境为了协调各类异步程序在单线程上有序执行的一套机制，运行在浏览器、跨端引擎以及Node.js中。</p>
<h3 id="事件循环简单的运行流程"><a href="#事件循环简单的运行流程" class="headerlink" title="事件循环简单的运行流程"></a>事件循环简单的运行流程</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> foo = <span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;First&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> bar = <span class="function">() =&gt;</span> <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;Second&#x27;</span>), <span class="number">500</span>)</span><br><span class="line"><span class="keyword">const</span> baz = <span class="function">() =&gt;</span> <span class="built_in">console</span>.log(<span class="string">&#x27;Third&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/javascript_event_loop.gif"></p>
<p>先解释一波，图中所示的三个区域：</p>
<ul>
<li><font color=green>Call Stack(调用栈)</font>：特点就是先进后出，这其实为了保证JS函数嵌套的时候，执行顺序能从里到外执行；</li>
<li><font color=red>WebAPIs(宿主环境的异步引擎)</font>：对各类异步程序进行分门别类的处理，<code>setTimeout</code>就按照毫秒参数倒计时，<code>XHR</code>就通过底层API发送请求等等；</li>
<li><font color=#c68206>Task Queue(任务队列)</font>：专门放置异步程序的回调函数，可多个任务排队；</li>
</ul>
<p>配合动图，走一遍执行流程：</p>
<ol>
<li>代码由上到下逐句执行，先把<code>foo()</code>放入<code>Call Stack</code>，由于不是异步程序直接输出<code>First</code>，同时把<code>foo()</code>函数清理出<code>Call Stack</code>；<strong>【First】</strong></li>
<li>执行到<code>bar()</code>，一样把函数放入<code>Call Stack</code>，发现是异步程序，抛给<code>WebAPIs</code>来处理，把<code>bar()</code>函数清理出<code>Call Stack</code>;</li>
<li>继续往下执行，执行到<code>baz()</code>，还是先放入<code>Call Stack</code>，不是异步程序，直接输出<code>Third</code>；<strong>【Third】</strong></li>
<li><code>WebAPIs</code>接收到定时器函数后，就滴答滴答的开始倒计时，就像参数设置的500毫秒后，把回调执行函数放入<code>Task Queue</code></li>
<li>检查<code>Call Stack</code>是清空状态后，放入定时器的回调执行函数，最后输出<code>Second</code>；<strong>【Second】</strong></li>
</ol>
<p>所以，控制台依次输出的日志是：<strong>First</strong> 、<strong>Third</strong> 、<strong>Second</strong></p>
<h3 id="理解宏任务-Task-与微任务-MicroTask"><a href="#理解宏任务-Task-与微任务-MicroTask" class="headerlink" title="理解宏任务(Task)与微任务(MicroTask)"></a>理解宏任务(Task)与微任务(MicroTask)</h3><ul>
<li>铺开列表一对比，区别很明显：<strong>宏任务基本和浏览器相关，而微任务则大多是ECMAScript级别的</strong>  </li>
</ul>
<table>
<thead>
<tr>
<th><strong>宏任务(Task)</strong></th>
<th><strong>微任务(Micro Task)</strong></th>
</tr>
</thead>
<tbody><tr>
<td>整体JavaScript代码段</td>
<td>Promise.then/catch/finally</td>
</tr>
<tr>
<td>渲染事件（解析DOM、layout计算布局、paint绘制）</td>
<td>await/async</td>
</tr>
<tr>
<td>DOM Event回调函数（点击事件、滚动页面、放大缩小）</td>
<td>MutationObserver</td>
</tr>
<tr>
<td>通过JS来调用事件</td>
<td>Object.observer</td>
</tr>
<tr>
<td>XHR网络请求</td>
<td>process.nextTick（Node.js独有）</td>
</tr>
<tr>
<td>I/O文件读写</td>
<td>Vue.nextTick（Vue提供的插入微任务队列的方法）</td>
</tr>
<tr>
<td>setTimeout定时器/setInterval轮询器</td>
<td>queueMicrotask</td>
</tr>
<tr>
<td>setImmediate</td>
<td></td>
</tr>
<tr>
<td>requestAnimationFrame</td>
<td></td>
</tr>
<tr>
<td>postMessage/MessageChannal</td>
<td></td>
</tr>
</tbody></table>
<h4 id="当前宏任务执行完毕（且调用栈被清空后）执行微任务"><a href="#当前宏任务执行完毕（且调用栈被清空后）执行微任务" class="headerlink" title="当前宏任务执行完毕（且调用栈被清空后）执行微任务"></a>当前宏任务执行完毕（且调用栈被清空后）执行微任务</h4><p><img src="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/eventloop-zhuanzhuan.jpg"></p>
<p>宏任务与微任务都是队列结构，逐个按顺序执行。当前宏任务执行完毕后执行微任务，微任务队列都被执行清空后，再执行下一个宏任务。每个宏任务执行完毕后，会检查是否进行浏览器渲染。</p>
<ul>
<li>示例1：微任务在当前宏任务后执行</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定时器属于宏任务</span></span><br><span class="line"><span class="built_in">setTimeout</span>( <span class="function"><span class="params">_</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="number">4</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">// promise属于微任务</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">  resolve()</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">1</span>)  <span class="comment">// 声明语句即时运行</span></span><br><span class="line">&#125;).then( <span class="function"><span class="params">_</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 微任务回调</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">3</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 按顺序输出1、2、3、4</span></span><br></pre></td></tr></table></figure>

<ul>
<li>实例2：手动触发事件与JS触发事件的区别</li>
</ul>
<p>JS触发事件相当于把两个click事件包装了起来，要等两个click宏任务执行完毕后，才会执行微任务</p>
<iframe width="100%" height="300" src="//jsrun.net/DR3Kp/embedded/html,result/light" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h3 id="事件循环机制与Vue-nextTick-和requestAnimationFrame-的关系"><a href="#事件循环机制与Vue-nextTick-和requestAnimationFrame-的关系" class="headerlink" title="事件循环机制与Vue.nextTick()和requestAnimationFrame()的关系"></a>事件循环机制与<code>Vue.nextTick()</code>和<code>requestAnimationFrame()</code>的关系</h3><p>讲到nextTick，首先要理解什么是一个Tick？每一轮循环就是一个Tick，对应当前的一个宏任务</p>
<blockquote>
<p>当前宏任务 → 微任务队列 → RAF → 更新渲染 → RIC → 下一个宏任务</p>
</blockquote>
<p>完整流程：</p>
<ul>
<li><code>Call Stack</code>清空后，开始从<code>Task queue</code>队列中放入排在最前面的宏任务，并执行它；</li>
<li>执行当前宏任务后，检查是否存在<code>Microtask</code>，如果有，则轮询执行，直到清空微任务队列（包含嵌套产生的微任务）；</li>
<li>检查是否进行浏览器渲染；</li>
<li>如需渲染，先调用requestAnimationFrame函数；</li>
<li>然后执行浏览器更新渲染；</li>
<li>最后执行requestIdleCallback函数；</li>
<li>重复以上步骤</li>
</ul>
<p>由于DOM更新也是微任务，所以<code>Vue.nextTick</code>的本质就是往<code>Microtask</code>队列后追加执行代码，从而保证能操作更新的DOM。</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903657264136200">微任务、宏任务与Event-Loop</a></li>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/uAU-fZi7ngg0vP6k2k83xg">JavaScript 事件循环：从起源到浏览器再到 Node.js</a></li>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/yfgE_60lipmKbUnP_B3MbA">一文讲解浏览器运行渲染机制、JS任务队列及事件循环</a></li>
<li><a target="_blank" rel="noopener" href="http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4=">loupe-事件循环可视化测试</a></li>
<li><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/267273074">大转转FE-当事件循环遇到更新渲染</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.poetries.top/browser-working-principle/guide/part4/lesson18.html#%E5%AE%8F%E4%BB%BB%E5%8A%A1">浏览器工作原理与实践</a></li>
<li><a target="_blank" rel="noopener" href="https://www.youtube.com/watch?v=cCOL7MC4Pl0&t=1598s&ab_channel=JSConf">JSConf-Jake Archibald Event Loop</a></li>
</ul>
<h2 id="未竟之事"><a href="#未竟之事" class="headerlink" title="未竟之事"></a>未竟之事</h2><ul>
<li>如何利用chrome performance观察事件循环</li>
<li>node.js与浏览器环境事件管理的区别</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/interview_questions/js/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6/" title="深入理解事件循环机制">https://gitee.com/lianghuilin/murmur.git/interview_questions/js/深入理解事件循环机制/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/vue3_practice/Vue3%E7%99%BB%E5%BD%95%E9%A1%B5%E7%9A%84%E8%83%8C%E6%99%AF%E5%A4%A7%E5%9B%BE%E8%BD%BD%E5%85%A5%E6%B8%90%E5%8F%98/" rel="prev" title="Vue3登录页的背景大图载入渐变">
                  <i class="fa fa-chevron-left"></i> Vue3登录页的背景大图载入渐变
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/vue2_explore/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3nextTick/" rel="next" title="深入理解nextTick">
                  深入理解nextTick <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
